package cn.walls1717.juc.rwlock;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁测试 <br>
 *
 * 只允许读读共存，读写和写写依然是互斥的，也就是一个资源可以被多个读操作访问或者只被一个写操作访问。
 * 只有在读多写少的情况下，读写锁才有较高的性能。<br>
 *
 * @author walls1717
 * @create 2022/12/19 20:36
 **/
@Slf4j
public class ReadWriteLockDemo {

    public static void main(String[] args) {

    }
}

@Slf4j
class MyResource {
    Map<String, String> map = new HashMap<>();
    Lock lock = new ReentrantLock();
    ReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void write(String key, String value) {
        lock.lock();
        try {
            log.info("正在写入");
            TimeUnit.MILLISECONDS.sleep(500);
            map.put(key, value);
            log.info("完成写入");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void read(String key) {
        lock.lock();
        try {
            log.info("正在读取");
            String s = map.get(key);
            TimeUnit.MILLISECONDS.sleep(200);
            log.info("完成读取 " + s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
